const mongoose = require("../db");
const Schema = mongoose.Schema;

const customerSchema = new Schema({
  customerId: { type: String, unique: true, required: true },
  name: { type: String, required: true },
  company: { type: String },
  phone: { type: String, required: true },
  email: { type: String },
  address: { type: String },
  tags: [{ type: String }],
  source: { 
    type: String, 
    enum: ['网站', '电话', '推荐', '广告', '其他'], 
    default: '其他' 
  },
  status: { 
    type: String, 
    enum: ['潜在客户', '意向客户', '成交客户', '流失客户'], 
    default: '潜在客户' 
  },
  assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
  createTime: { type: Date, default: Date.now },
  updateTime: { type: Date, default: Date.now }
});

// 创建索引
customerSchema.index({ customerId: 1 });
customerSchema.index({ phone: 1 });
customerSchema.index({ email: 1 });
customerSchema.index({ assignedTo: 1 });
customerSchema.index({ createTime: -1 });

// 更新时间中间件
customerSchema.pre('save', function(next) {
  this.updateTime = new Date();
  next();
});

customerSchema.pre('findOneAndUpdate', function(next) {
  this.set({ updateTime: new Date() });
  next();
});

module.exports = mongoose.model("Customer", customerSchema);